package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.DishVO;
import org.apache.http.MessageConstraintException;
import org.apache.http.client.HttpClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
     private UserMapper userMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetMealMapper setMealMapper;

    @Override
    public User login(UserLoginDTO dto) {
       Map<String,String> map=new HashMap<>();
       map.put("appid",weChatProperties.getAppid());
       map.put("secret",weChatProperties.getSecret());
       map.put("js_code",dto.getCode());
       map.put("grant_type","authorization_code");
        String josnResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session?", map);
        JSONObject jsonObject = JSONObject.parseObject(josnResult);
        String openId = jsonObject.getString("openid");
            if (openId==null){
                throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
            }
           User user = userMapper.getUserByOpenId(openId);
            if (user==null){
                User newUser = User.builder()
                        .openid(openId)
                        .createTime(LocalDateTime.now()).build();
                userMapper.saveUser(newUser);
                return newUser;

            }

        return user;
    }

    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart=new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        if (shoppingCart.getSetmealId() != null){
          Setmeal setmeal = categoryMapper.getsetmealBySetmealId(shoppingCart.getSetmealId());
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setAmount(setmeal.getPrice());
            shoppingCart.setSetmealId(setmeal.getId());
            List<ShoppingCart> lists= userMapper.getShoppingCartsById(shoppingCart);
            if (lists != null && lists.size() == 1){
                ShoppingCart sc = lists.get(0);
                shoppingCart.setNumber(sc.getNumber()+1);
                shoppingCart.setId(sc.getId());
                userMapper.updateShoppingCart(shoppingCart);
            }else {
                shoppingCart.setNumber(1);
                userMapper.addShoppingCart(shoppingCart);
            }
        }else {
            DishVO dishById = categoryMapper.getDishById(shoppingCart.getDishId());
            shoppingCart.setDishId(dishById.getId());
            shoppingCart.setName(dishById.getName());
            shoppingCart.setAmount(dishById.getPrice());
            shoppingCart.setDishId(dishById.getId());
            List<ShoppingCart> dishs = userMapper.getShoppingCartsById(shoppingCart);
            if (dishs != null && dishs.size() == 1){
                ShoppingCart dish = dishs.get(0);
                shoppingCart.setNumber(dish.getNumber()+1);
                shoppingCart.setId(dish.getId());
                userMapper.updateShoppingCart(shoppingCart);
            }else {
                shoppingCart.setNumber(1);
                userMapper.addShoppingCart(shoppingCart);
            }
        }
    }

    @Override
    public void cleanShoppingCart() {
        userMapper.cleanShoppingCart(BaseContext.getCurrentId());
    }

    @Override
    public List<ShoppingCart> getshoppingCartList() {

        return userMapper.getshoppingCartList(BaseContext.getCurrentId());
    }

    @Override
    public void deleteShoppingCart(ShoppingCartDTO shoppingCartDTO) {
      ShoppingCart  shoppingCart = new ShoppingCart();
      BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
      shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = userMapper.getShoppingCartsById(shoppingCart);
        if(list.get(0).getNumber()-1 == 0){
            userMapper.deleteShoppingCart(list.get(0));
        }else {
            list.get(0).setNumber(list.get(0).getNumber()-1);
            userMapper.updateShoppingCart(list.get(0));
        }


    }
}
